import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class PhotoAppPage extends StatefulWidget {
  @override
  _PhotoAppPageState createState() => _PhotoAppPageState();
}

class _PhotoAppPageState extends State<PhotoAppPage> {
  List<File> _images = [];

  Future getImage(bool isPhoto) async {
    Navigator.pop(context);
    var image = await ImagePicker.pickImage(
        source: isPhoto ? ImageSource.camera : ImageSource.gallery);
    setState(() {
      _images.add(image);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('相机使用'),
      ),
      body: Padding(padding: EdgeInsets.all(5),
      child: Wrap(
        spacing: 5,
        runSpacing: 5,
        children: _getImages(),
      ),),
      floatingActionButton: FloatingActionButton(
        onPressed: _pickImageType,
        tooltip: 'Pick Image',
        child: Icon(Icons.add_a_photo),
      ),
    );
  }

  _pickImageType() {
    showModalBottomSheet(
        context: context,
        builder: (context) => Container(
              height: 160,
              child: Column(
                children: <Widget>[
                  _item("拍照", true),
                  _item("从相册选择", false),
                ],
              ),
            ));
  }

  _item(String title, bool isPhoto) {
    return GestureDetector(
      child: ListTile(
        leading: Icon(isPhoto ? Icons.camera_alt : Icons.photo_library),
        title: Text(title),
        onTap: () => getImage(isPhoto),
      ),
    );
  }

  _getImages() {
    return _images.map((file) {
      return Stack(
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.circular(5),
            child: Image.file(
              file,
              width: 120,
              height: 90,
              fit: BoxFit.fill,
            ),
          ),
          Positioned(right: 5, top: 5, child: GestureDetector(
            onTap: (){
              setState(() {
                _images.remove(file);
              });
            },
            child: ClipOval(
              child: Container(
                padding: EdgeInsets.all(4),
                decoration: BoxDecoration(color: Colors.black26),
                child: Icon(Icons.close,size: 15,color: Colors.white,),
              ),
            ),
          ))
        ],
      );
    }).toList();
  }
}
